package com.hspedu.copyfile;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author 谷其昊
 * @version 1.0
 * @date 2022/3/2
 * @time 18:31
 */
public class TCPFileUploadServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("服务器开始监听...");
        //监听
        Socket accept = serverSocket.accept();

        //创建输出流保存图片
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("D:\\BaiduNetdiskDownload\\韩顺平2021基础学Java\\mytemp\\hnt.png"));

        //读取图片并保存
        InputStream inputStream = accept.getInputStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
        byte[] buffer = new byte[1024];
        int readLength = 0;
        while ((readLength = bufferedInputStream.read(buffer)) != -1){
            bufferedOutputStream.write(buffer,0,readLength);
        }
        bufferedOutputStream.flush();

        //向客户端发送信息
        OutputStream outputStream = accept.getOutputStream();
        BufferedOutputStream bufferedOutputStream1 = new BufferedOutputStream(outputStream);
        bufferedOutputStream1.write("收到图片".getBytes());
        //一定要刷新，将数据刷新进通道
        bufferedOutputStream1.flush();
        accept.shutdownOutput();


        accept.close();
        serverSocket.close();
    }
}
